package com.tstudy.laoshibang.camera;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;
import com.tstudy.laoshibang.utils.SharedPreferencesUtil;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
/**
 * 
* @CopyRight xinweitech.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date 2015年4月9日 下午5:58:23
 */
@SuppressWarnings("deprecation")
@EFragment(R.layout.camera)
public class CameraFragment extends BaseFragment {
	public static String TAG = "camera";
	@ViewById(R.id.camera_root)
	View mRootLayout;
	@ViewById(R.id.camera_button_layout)	
	ViewGroup mButtonLayout;
	@ViewById(R.id.camera_preview)
	FrameLayout mPreviewLayout;
	
	private CameraPreview mPreview;
	private Camera mCamera = null;
	private Camera.Parameters myParameters;
	private Camera.AutoFocusCallback mAutoFocusCallback;
	private boolean mIsPortrait;
	Handler mHandler;
	public CameraFragment() {
		super();
	}
	
	int bottomHeight = (int)BaseApplication.mContext.getResources().getDimension(R.dimen.camera_bottom_height);
	public static void add(int containerViewId,boolean isPortrait){
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		args.putBoolean(CONSTANT.ARGS.IS_PORTRAIT, isPortrait);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,CameraFragment_.class.getName(), args);
		((BaseActivity)BaseApplication.mCurrentActivity).add(containerViewId,fragment,TAG,false);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		if (mRootLayout != null) {
			((ViewGroup)mRootLayout.getParent()).removeAllViews();
		}
		return null;//must return null
	}
	@Override
	public void onStart() {
		super.onStart();
	}

	@AfterViews
	public void initView() {
		initCamera();
		initAutoFocusCallback();
		mPreview = new CameraPreview(getActivity(), mCamera);
		mPreviewLayout.addView(mPreview);
	}
	
	@Click(R.id.camera_button_cancel)
	public void cancelClick() {
			getActivity().finish();
	}
	
	@Click(R.id.camera_button_take)
	public void takePhoto() {
		if (mCamera != null) {
			mCamera.takePicture(myShutterCallback, myRawCallback, myjpegCalback);
		}
	}

	/**
	 * 打开相册
	 */
	@Click(R.id.camera_button_album)
	public void openLibrary() {
		Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
		getImage.addCategory(Intent.CATEGORY_OPENABLE);
		getImage.setType("image/jpeg");
		startActivityForResult(getImage,CONSTANT.REQUEST_CODE_ALBUM);
	}
	
	PictureCallback myRawCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
		}
	};

	PictureCallback myjpegCalback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			CommonUtil.recycleBm(BaseApplication.mCameraBM);
            BaseApplication.mCameraBM = CommonUtil.resizeImage(data,BaseApplication.mScreenWidth,BaseApplication.mScreenHeight-bottomHeight);
            if (SharedPreferencesUtil.getSavePhoto()) {
				new SaveTakePhotoTask().execute(BaseApplication.mCameraBM);
			}
			LogUtil.d("onPictureTaken... width:%d...height:%d", BaseApplication.mCameraBM.getWidth(),BaseApplication.mCameraBM.getHeight());
			data = null;
			setPushParameters(CONSTANT.CAMARA_ROTATION_DEGREE);
		}
	};
	
	class SaveTakePhotoTask extends AsyncTask<Bitmap, Object, Boolean>{
		@Override
		protected Boolean doInBackground(Bitmap... params) {
			String result = CommonUtil.saveImage(CommonUtil.getTakePhotoSavePath(), params[0]);
			if (!TextUtils.isEmpty(result)) {
				CommonUtil.inserMideaLibrary(BaseApplication.mContext, result);
			}
			return result == null;
		};
	}

	private void setPushParameters(final int orientation) {
		mButtonLayout.setVisibility(View.INVISIBLE);
		mPreviewLayout.setVisibility(View.INVISIBLE);
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				CropperFragment.add(mFragmentId,mIsPortrait, orientation);
			}
		}, 500);
	}
	
	public void initAutoFocusCallback(){
		mAutoFocusCallback = new Camera.AutoFocusCallback() {
			public void onAutoFocus(boolean success, Camera camera) {
				if (success) {
					try {
						mCamera.setOneShotPreviewCallback(null);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		};
	}
	public void initCamera() {
		if (mCamera == null) {
			try {
				mCamera = Camera.open();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (mCamera != null) {
			try {
				myParameters = mCamera.getParameters();
				myParameters.setPictureFormat(PixelFormat.JPEG);
				myParameters.set("orientation", "portrait");
				mCamera.setDisplayOrientation(CONSTANT.CAMARA_ROTATION_DEGREE);
				mCamera.setParameters(myParameters);
				mCamera.autoFocus(mAutoFocusCallback);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	

	private ShutterCallback myShutterCallback = new ShutterCallback() {

		public void onShutter() {
			// TODO Auto-generated method stub

		}
	};
	
	

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
	
	@Override
	public void onStop() {
		super.onStop();
	}
	@Override
	public void onDestroyView() {
		if (mCamera != null) {
			mCamera.setPreviewCallback(null) ;
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;
			mPreview = null;
		}
		mPreviewLayout.removeAllViews();
		super.onDestroyView();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void clear() {
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mIsPortrait = args.getBoolean(CONSTANT.ARGS.IS_PORTRAIT);
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtil.d("--CameraFragment requestCode==" + requestCode + "--resultCode==" + resultCode);
		ContentResolver resolver = BaseApplication.mContext.getContentResolver();
		if (requestCode == CONSTANT.REQUEST_CODE_ALBUM && data != null) {//For camera album image
			try {
				Uri originalUri = data.getData();
				int orientation = CommonUtil.getAlbumOrientation(originalUri);
				byte[] sAlbumBytes = CommonUtil.readStream(resolver.openInputStream(Uri.parse(originalUri.toString())));
				CommonUtil.recycleBm(BaseApplication.mCameraBM);
				BaseApplication.mCameraBM = CommonUtil.resizeImage(sAlbumBytes,BaseApplication.mScreenWidth,BaseApplication.mScreenHeight-bottomHeight);
				sAlbumBytes = null;
				setPushParameters(orientation);
			} catch (Exception e) {
			}

		} else if (requestCode == 1) {
		}
	}

}
